package com.hna.face.controller.business;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hna.face.base.BaseController;
import com.hna.face.common.result.BaseResult;
import com.hna.face.model.*;
import com.hna.face.service.IFacePersonService;
import com.hna.face.service.IFacePhotoLibService;
import com.hna.face.service.IFaceScheduleService;
import com.hna.face.service.IFaceSyncInfoService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class FaceController extends BaseController {

	@Value("${photo_dir}")
	public  String photoDir;
	
	@Autowired
	IFacePhotoLibService facephotoLabService;

	@Autowired
	IFacePersonService facePersonService;

	@Autowired
	IFaceScheduleService faceScheduleService;

	@Autowired
	IFaceSyncInfoService faceSyncInfoService;

	private final static Logger log = LoggerFactory.getLogger(FaceController.class);

	@RequestMapping("/face/index")
	public String index() {
		return "pages/face/index";
	}

	@RequestMapping("/face/add")
	public String add(HttpServletRequest request,String name) {
		request.setAttribute("name", name);
		return "pages/face/add";
	}

	@RequestMapping("/face/addphoto")
	public String addphoto(HttpServletRequest request,String name) {
		request.setAttribute("name", name);
		return "pages/face/upload";
	}
	

//    @RequestMapping("/face/detail")
//    public ModelAndView details(HttpServletRequest request) {
//        ModelAndView modelAndView = new ModelAndView("pages/face/detail");
//        modelAndView.addObject("id", request.getParameter("id"));
//        return modelAndView;
//    }
//    
//    
//    @RequestMapping("/face/edit")
//	public ModelAndView edit(HttpServletRequest request) {
//		ModelAndView modelAndView = new ModelAndView("pages/face/edit");
//		modelAndView.addObject("id", request.getParameter("id"));
//		return modelAndView;
//	}

	@RequestMapping(value = { "/rest/face/list" }, method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> list(HttpServletRequest request, PageInfo pageInfo, FacePhotoLib face,String name) {
		Map<String, Object> res = new HashMap<>();
		try {
			Wrapper<FacePhotoLib> wrapper = new EntityWrapper<>();
			wrapper.eq("name",name);
			face = facephotoLabService.selectOne(wrapper);
			Page<FacePhotoLib> page = new Page<>(pageInfo.getPage(), pageInfo.getRows());
			Page<FacePhotoLib> faceList = facephotoLabService.selectPage(page, wrapper);

			res.put("rows", faceList.getRecords());
			res.put("total", faceList.getTotal());
			res.put("success", "true");
			return res;
		} catch (Exception e) {
			res.put("success", "false");
			return res;
		}
	}

	@RequestMapping("/rest/face/info")
	public @ResponseBody BaseResult info(HttpServletRequest request) {
		Long id = Long.parseLong(request.getParameter("id"));
		FacePhotoLib face = facephotoLabService.selectById(id);
		return BaseResult.success(face);
	}

	@RequestMapping(value = { "/rest/face/del" }, method = RequestMethod.POST)
	public @ResponseBody BaseResult del(HttpServletRequest request, String ids) {
		try {

			if (StringUtils.isEmpty(ids)) {
				return BaseResult.success();
			}
			List<String> asList = Arrays.asList(ids.split(","));
			facephotoLabService.deleteBatchIds(asList);
			for (String id: asList
				 ) {
				this.syninfo(Long.valueOf(id),2);
			}
			return BaseResult.success();
		} catch (Exception e) {
			log.error("发生异常了", e);
			return BaseResult.fail(e.getMessage());
		}
	}

	/**
	 * 保存图片
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = { "/rest/face/saveImg" }, method = RequestMethod.POST)
	public @ResponseBody String saveImg(HttpServletRequest request, HttpServletResponse response) {
		// 图片的名字返回前台
		String imageName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + ".jpg";
		try {
			String imageDataUrl = request.getParameter("image");
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] b = decoder.decodeBuffer(imageDataUrl);
			ByteArrayInputStream bais = new ByteArrayInputStream(b);
			BufferedImage bi1 = ImageIO.read(bais);
			// "D://image/" photoDir
			log.info("path:"+photoDir + imageName);
			File w2 = new File(photoDir + imageName);
			ImageIO.write(bi1, "jpg", w2);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return imageName;
	}

	@RequestMapping(value = { "/rest/face/saveData" }, method = RequestMethod.POST)
	@ResponseBody
	public BaseResult saveData(String imageName,@RequestParam("name")String name,HttpServletRequest request,Integer type) {
		
		System.out.println(name + "----");
		System.out.println(imageName + "---------------------------------------");
		// 1、把name数据插入到photo_person这张表中，插入完成后返回一个这条数据的photo_person_id
		Wrapper<FacePerson> wrapper = new EntityWrapper<>();
//    	PhotoPerson photoPerson = new PhotoPerson();
//    	photoPerson.setName(name);
//    	this.PhotoPersonService.insert(photoPerson);

		wrapper.eq("name", name);
		FacePerson p = facePersonService.selectOne(wrapper);
		// 2、把图片的名字imageName进行切割，获取每一个名字
		String[] split = imageName.split(",");
		FacePhotoLib facePhotoLib = new FacePhotoLib();
		for (int i = 0; i < split.length; i++) {
			String photo = split[i];
			// 调用插入photo_lab的方法，循环往photo_lab表中插入数据.
			facePhotoLib.setPersonId(p.getId());
			facePhotoLib.setPhoto(photo);
			facePhotoLib.setName(name);
			facePhotoLib.setType(type);
			facePhotoLib.setCreateTime(new Date());
			facePhotoLib.setUpdateTime(new Date());
			facephotoLabService.insert(facePhotoLib);
			this.syninfo(facePhotoLib.getId(),1);
		}

		/*List<Long> list = new ArrayList<>();
		Wrapper<FacePhotoLib> wrapper1 = new EntityWrapper<>();
		wrapper1.eq("personId", personId);
		List<FacePhotoLib> photoLabs = facephotoLabService.selectList(wrapper1);
		// 根据Maxid查询他图片表的所有id 返回到http://106.2.20.167:81/faceApi/addPhoto?ids=257,258
		for (FacePhotoLib po : photoLabs) {
			list.add(po.getId());
		}*/
		return BaseResult.success();
	}

	@RequestMapping(value = { "/rest/face/uploadsave" }, method = RequestMethod.POST)
	public BaseResult save(HttpServletRequest request, HttpServletResponse response, String name,Integer type,
			@RequestParam("photo") MultipartFile[] files) {
			Wrapper<FacePerson> wrapper = new EntityWrapper<>();
			wrapper.eq("name",name);
			FacePerson facePerson = facePersonService.selectOne(wrapper);
			if(facePerson == null) {
				facePerson.setName(name);
				facePerson.setCreateTime(new Date());
		    	this.facePersonService.insert(facePerson);

				/*Wrapper<FaceSchedule> wrapper1 = new EntityWrapper<>();
				wrapper1.eq("person_id", facePerson.getId());
				FaceSchedule faceSchedule = this.faceScheduleService.selectOne(wrapper1);*/
				FaceSyncInfo faceSyncInfo = new FaceSyncInfo();
				faceSyncInfo.setTableName("face_person");
				faceSyncInfo.setRecordId(facePerson.getId());
				faceSyncInfo.setOpt(1);
				faceSyncInfo.setStatus(1);
                faceSyncInfo.setCreateTime(new Date());
				/*faceSyncInfo.setVehicleId(faceSchedule.getVehicleId());
				faceSyncInfo.setVehicleNo(faceSchedule.getVehicleNo());*/
				this.faceSyncInfoService.insert(faceSyncInfo);
		    }
			
		try {
			for (MultipartFile file : files) {
				/*long timeStamp = new Date().getTime();
				long startTime = System.currentTimeMillis();*/
				String imageName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
				// "D://image/" photoDir
				String path = photoDir+ imageName+ ".jpg";
				log.info("path:"+path);
				File newFile = new File(path);
				// 通过CommonsMultipartFile的方法直接写文件（注意这个时候）
				file.transferTo(newFile);
				
				FacePhotoLib face = new FacePhotoLib();
				face.setName(name);
				face.setPhoto(imageName + ".jpg");
				face.setCreateTime(new Date());
				face.setUpdateTime(new Date());
				face.setPersonId(facePerson.getId());
				face.setType(type);
				facephotoLabService.insert(face);
				this.syninfo(face.getId(),1);
			}
			return BaseResult.success();
		} catch (Exception e) {
			log.error("发生异常了", e);
			return BaseResult.fail(e.getMessage());
		}
	}
	

	@RequestMapping(value = { "/rest/face/update" }, method = RequestMethod.POST)
	public @ResponseBody BaseResult update(HttpServletRequest request, FacePhotoLib face, String meterNo) {
		Map<String, Object> res = new HashMap<>();
		try {
//        	face.setMeterNo(meterNo);
			facephotoLabService.updateById(face);
			this.syninfo(face.getId(),3);
//        	MjMeter meter = new MjMeter();
//        	meter.setfaceId(face.getId());
//        	meter.setInstallTime(face.getRegisteredTime());
//        	meter.setMeterId(meterId);
//			meterService.insert(meter );

			return BaseResult.success();
		} catch (Exception e) {
			log.error("发生异常了", e);
			return BaseResult.fail(e.getMessage());
		}
	}
	private void syninfo(Long id,Integer opt) {
		/*FacePhotoLib facePhotoLib = this.facephotoLabService.selectById(id);
		Wrapper<FaceSchedule> wrapper = new EntityWrapper<>();
		wrapper.eq("person_id", facePhotoLib.getPersonId());
		FaceSchedule faceSchedule = this.faceScheduleService.selectOne(wrapper);*/
		FaceSyncInfo faceSyncInfo = new FaceSyncInfo();
		faceSyncInfo.setTableName("face_photo_lib");
		faceSyncInfo.setRecordId(id);
		faceSyncInfo.setOpt(opt);
		faceSyncInfo.setStatus(1);
        faceSyncInfo.setCreateTime(new Date());
		/*faceSyncInfo.setVehicleId(faceSchedule.getVehicleId());
		faceSyncInfo.setVehicleNo(faceSchedule.getVehicleNo());*/
		this.faceSyncInfoService.insert(faceSyncInfo);
	}

}

class SalaryListRequest {
	private String year;
	private String month;
	private String status;

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}

	public String getMonth() {
		return month;
	}

	public void setMonth(String month) {
		this.month = month;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

}
